<template>
  <div>
    <!-- 搜索栏 -->
    <search-bar @onSearch="onSearch" />
    <!-- /搜索栏 -->

    <el-button type="primary" @click="handleAdd"><el-icon><Plus /></el-icon>新增
    </el-button>

    <el-table v-loading="loading" :data="cateList" :header-cell-style="{ 'background': '#f8f8f9', height: '50px' }"
      row-key="id" :tree-props="{ children: 'children' }" highlight-current-row>
      <el-table-column prop="cateName" label="分类名" align="center"></el-table-column>
      <el-table-column prop="enable" label="是否启用" align="center">
        <template #default="{ row }">
          <el-switch inline-prompt @change="switchCateState(row.id, row.enable)" v-model="row.enable" active-text="显示"
            inactive-text="隐藏" />
        </template>
      </el-table-column>
      <el-table-column prop="icon" label="图标" align="center">
        <template #default="{ row }">
          <el-image preview-teleported style="width: 40px;height: 40px;border-radius: 50%;" :src="row.icon"
            :preview-src-list="[row.icon]" />
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center">
        <template #default="{ row }">
          <el-button type="primary" text  @click="handleUpdate( row.id )">编辑</el-button>
          <el-button type='danger' text @click="handleDelete( row.id )">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加或修改公告对话框 -->
    <el-dialog :title="title" v-model="open" width="600px" append-to-body>
      <el-form :rules="rules" ref="cateAdd" :model="form" label-width="120px">
    <el-form-item label="分类名" prop="cateName">
      <el-input v-model="form.cateName" />
    </el-form-item>
    <el-form-item label="使用启动" prop="enable">
      <el-switch
          v-model="form.enable"
          inline-prompt
          style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
          active-text="启用"
          inactive-text="禁用"
        />
    </el-form-item>
    <el-form-item label="父级分类" prop="pid">
      <el-cascader v-model="form.pid" :options="cateList" :props="cascaderProps" clearable />
    </el-form-item>
    <!-- <el-form-item label="分类图标">
      <el-upload
        list-type="picture-card"
        action="/api/upload"
        name="file"
        accept="image/*"
        :on-success="uploadSuccess"
        :before-upload="beforeUpload"
        class="avatar-uploader"
  >
       <el-icon><Plus /></el-icon>

    <template #file="{ file }">
      <div>
        <img class="el-upload-list__item-thumbnail " :src="file.url" alt="" />
      </div>
    </template>
  </el-upload>
    </el-form-item> -->

    <el-form-item label="分类图标">
      <el-upload
        action="/api/upload"
        name="file"
        accept="image/*"
        :on-success="uploadSuccess"
        :before-upload="beforeUpload"
      >
        <el-button>上传</el-button>
      </el-upload>
      <el-image  style="width: 100px;" :src="form.icon" :preview-src-list="[form.icon]"/>
    </el-form-item>

    <el-form-item>
      <el-button type="primary" @click="submitForm">提交</el-button>
      <el-button @click="cancel">取消</el-button>
    </el-form-item>
  </el-form>
    </el-dialog>

    <!-- 分页 -->
    <el-pagination layout="prev, pager, next, jumper, sizes"
     v-model:page-size="pageSize"

     v-model:current-page="page"
      :total="total" />
    <!-- /分页 -->
  </div>
</template>

<script>
import { listCate, addCate, getCateDetail, updateCate, delCate } from '@/api/cateList/cateList.js'
import SearchBar from '@/components/SearchBar.vue'

export default {
  name: 'CateList',
  data () {
    return {
      // 表单参数
      form: {},
      cascaderProps: {
        emitPath: false,
        checkStrictly: true,
        value: 'id',
        label: 'cateName'
      },
      total: 0,
      page: 1,
      pageSize: 10,
      cateList: [],
      // 遮罩层
      loading: true,
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 查询参数
      searchParams: {},
      // 校验
      rules: {
        cateName: [
          { required: true, message: '分类名不能为空', trigger: 'blur' }
          /* {
            validator: (rule, value) => {
              if (value === '小明') {
                return true
              } else {
                return false
              }
            },
            message: '必须输入小明'
          } */
          // {
          //   pattern: /^[a-zA-Z]\w{3,7}$/,
          //   message: '4-8位字母数字下划线组成,必须字母开头'
          // }
        ]
      }
    }
  },

  created () {
    this.getCateList()
  },

  components: {
    SearchBar
  },

  methods: {
    beforeUpload (file) {
      console.log(file)
      // 上传之前 限制 文件大小 体积不能超过 1m
      if (file.size > 1024 * 1024) {
        this.$message({
          type: 'error',
          message: '图片体积不能超出1m'
        })
        return false
      } else {
        return true
      }
    },
    uploadSuccess (res) {
      // 上传成功
      if (res.code === 200) {
        this.form.icon = res.data.url
        this.$message({
          type: 'success',
          message: '上传成功'
        })
      }
    },

    /** 新增按钮操作 */
    handleAdd () {
      this.reset()
      this.open = true
      this.title = '新增商品分类'
    },

    /** 编辑按钮操作 */
    handleUpdate (row) {
      getCateDetail(row.id).then(res => {
        this.form = res.data.data
        this.open = true
        this.title = '编辑商品分类'
      })
    },

    /** 删除按钮操作 */
    handleDelete (row) {
      this.$confirm('此操作会彻底删除该数据,继续吗?', '删除').then(() => {
        delCate(row.id).then(res => {
          if (res.data.code === 200) {
            this.$message({
              type: 'success',
              message: res.data.msg,
              duration: 1000,
              onClose: () => {
                this.getCateList()
              }
            })
          }
        })
      })
    },

    /** 获取商品分类列表数据 */
    getCateList () {
      listCate({
        ...this.searchParams,
        page: this.page,
        pageSize: this.pageSize
      }).then(res => {
        if (res.data.code === 200) {
          this.cateList = res.data.data.lists
          this.total = res.data.data.total
          this.loading = false
        }
      })
    },

    submitForm () {
      // 提交之间 判断 所有的 表单验证规则 是否都通过 通过则 提交 否则 弹出错误提示
      /* this.$refs.cateAdd.validate(valid => {
        console.log(valid)
      }) */
      this.$refs.cateAdd.validate().then(() => {
        // 在这里发送请求
        if (this.form.id === '') {
          addCate(this.form).then(res => {
          // 弹出提示框 告诉用户是否成功或者失败
            if (res.data.code === 200) {
              this.open = false
              this.$message({
                type: 'success',
                duration: 1000,
                message: res.data.msg,
                onClose: () => {
                // 刷新列表
                  this.getCateList()
                }
              })
            } else {
              this.$message({
                type: 'error',
                message: res.data.data.msg
              })
            }
          })
        } else {
          updateCate(this.form).then(res => {
          // 弹出提示框 告诉用户是否成功或者失败
            if (res.data.code === 200) {
              this.open = false
              this.$message({
                type: 'success',
                duration: 1000,
                message: res.data.msg,
                onClose: () => {
                // 刷新列表
                  this.getCateList()
                }
              })
            } else {
              this.$message({
                type: 'error',
                message: res.data.data.msg
              })
            }
          })
        }
      }).catch(() => {
        // 弹出错误提示
        this.$message({
          type: 'error',
          duration: 1000,
          message: '表单验证失败'
        })
      })
    },

    cancel () {
      this.reset()
      this.open = false
    },

    // 表单重置
    reset () {
      this.form = {
        id: '',
        cateName: '',
        enable: '',
        icon: '',
        pid: -1 // 当前分类父级分类的id -1代表没有父级分类 是顶层分类
      }
    },

    // 行内修改分类显示隐藏状态
    switchCateState (id, enable) {
      updateCate({
        id,
        enable
      }).then(res => {
        if (res.data.code === 200) {
          this.$message({
            type: 'success',
            message: res.data.msg,
            duration: 1000
          })
        }
      })
    },

    // 点击搜索
    onSearch (searchParams) {
      this.searchParams = searchParams
      this.getCateList()
    }
  },

  watch: {
    // 监听当前页 和 一页多少条 重新发送请求 实现分页数据处理
    page () {
      this.getCateList()
    },
    pageSize () {
      this.getCateList()
    }
  }
}
</script>

<style lang="scss" scoped>
.avatar-uploader{
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
}

.avatar-uploader >>> .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 80px;
  height: 60px;
  line-height: 76px;
  text-align: center;
}

.avatar {
  width: 80px;
  height: 60px;
  display: block;
}
</style>
